package common.fengkai.filepost.utils;

import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.util.GUID;
import cfca.paperless.util.StringUtil;
import common.fengkai.filepost.conf.PaperlessConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
/**
 * 获取cfca证书信息工具类
 */

/**
    pdf无法获取国密加密的证书，调用无纸化的接口获取证书信息
 */
@Slf4j
public class GetSealInfoUtil {

    /**
     *
     * @param bytes pdf文件流
     * @return sealIntoOrg 发证机构  sealIntoTitle 证书标题  sealIntoNo 证书编号
     * @throws Exception
     */
    public static Map<String,String> getSealInfo(byte[] bytes) throws Exception {
        HashMap<String, String> sealInfo = new HashMap<>();
        //无纸化服务客户端
        PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.url, 10000, 60000);
        String systemNo = GUID.generateId();
        String verifyStrategyXml = "<Request><SealVerifyType>0</SealVerifyType></Request>";
        String result = clientBean.verifyPdfSignature(systemNo, bytes, verifyStrategyXml, PaperlessConfig.operatorCode, PaperlessConfig.channelCode);
        String code = StringUtil.getXmlField(result, "Code");
        if ("200".equals(code)) {
            log.info("VerifyPdfSignature END OK");
            log.debug(result);

            int esealtitleStartIndex = result.indexOf("<Dn>")+4;
            int esealtitleEndIndex = result.indexOf("</Dn>");
            String esealtitle = result.substring(esealtitleStartIndex, esealtitleEndIndex);
            sealInfo.put("sealIntoTitle",esealtitle);

            int serialNoStartIndex = result.indexOf("<SerialNo>")+10;
            int serialNoEndIndex = result.indexOf("</SerialNo>");
            String serialNo = result.substring(serialNoStartIndex, serialNoEndIndex);
            sealInfo.put("sealIntoNo",serialNo);

            int orgNoStartIndex = result.indexOf("<IssuerDn>")+10;
            int orgNoEndIndex = result.indexOf("</IssuerDn>");
            String orgName = result.substring(orgNoStartIndex, orgNoEndIndex);
            sealInfo.put("sealIntoOrg",orgName);
        } else {
            // 处理结果为异常，打印出错误码和错误信息
            log.debug("VerifyPdfSignature END NG");
            log.debug(result);

        }
        return sealInfo;
    }
}
